package com.lambkit.module.pay.web.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.jfinal.kit.PropKit;
import com.lambkit.common.util.RequestUtils;
import com.lambkit.module.pay.common.PayConstant;
import com.lambkit.web.controller.LambkitController;

import java.util.Map;

/**
 * 支付宝
 * Created by ZhangShuzheng on 2017/04/04.
 */
//@Controller
//@RequestMapping("/alipay")
public class AlipayController extends LambkitController {

    private AlipayClient alipayClient;

    private AlipayTradeWapPayRequest alipayTradeWapPayRequest;

    private AlipayTradePagePayRequest alipayTradePagePayRequest;

    // 电脑网站支付
    //@RequestMapping("/pay/pc")
    //@ResponseBody
    public void pc() {
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "pay2017" + System.currentTimeMillis());
        bizContent.put("total_amount", "0.01");
        bizContent.put("subject", "Iphone6 16G");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayTradePagePayRequest.setBizContent(bizContent.toString());
        String result = null;
        try {
			result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
        renderHtml(result);
    }

    // 手机网站支付
    //@RequestMapping("/pay/wap")
    //@ResponseBody
    public void wap() {
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "pay2017" + System.currentTimeMillis());
        bizContent.put("total_amount", "0.01");
        bizContent.put("subject", "Iphone6 16G");
        bizContent.put("product_code", "QUICK_WAP_PAY");
        alipayTradeWapPayRequest.setBizContent(bizContent.toString());
        String result = null;
        try {
			result = alipayClient.pageExecute(alipayTradeWapPayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
        renderHtml(result);
    }

    // 异步通知
    //@RequestMapping("/notifyUrl")
    //@ResponseBody
    public void notifyUrl() throws Exception {
        Map<String, String> parameterMap = RequestUtils.getParameterMap(getRequest());
        // 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(
                parameterMap,
                PropKit.get("alipay.alipay_public_key"),
                PropKit.get("alipay.charset"),
                PropKit.get("alipay.sign_type"));
        if (!signVerified) {
            renderText(PayConstant.FAILED);
        } else {
        	renderText(PayConstant.SUCCESS);
        }
    }

}